package com.chuang.bootplus.controller.topic;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.chuang.bootplus.base.exception.BusException;
import com.chuang.bootplus.base.utils.ApiResponse;
import com.chuang.bootplus.base.utils.BeanUtil;
import com.chuang.bootplus.entity.document.Document;
import com.chuang.bootplus.entity.model.River;
import com.chuang.bootplus.entity.topic.TMapD;
import com.chuang.bootplus.entity.topic.TMapLastname;
import com.chuang.bootplus.entity.topic.TMapW;
import com.chuang.bootplus.entity.topic.Topic;
import com.chuang.bootplus.mapper.TopicMapper;
import com.chuang.bootplus.model.*;
import com.chuang.bootplus.service.*;
import com.chuang.bootplus.vo.IndexVO;
//import com.chuang.bootplus.vo.RiverVO;
import com.chuang.bootplus.vo.RiverVO;
import com.chuang.bootplus.vo.TopicMinVO;
import com.chuang.bootplus.vo.TopicVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author chang
 * @since 2022-06-21
 */
@RestController
@Api(tags = {"Topic"})
@RequestMapping("/topic")
@Slf4j
public class TopicController {


    @Autowired
    DocumentService documentService;

    @Autowired
    TMapDService tMapDService;

    @Autowired
    TopicService topicService;

    @Autowired
    TMapWService tMapWService;


    @Autowired
    TMapLastnameService tMapLastnameService;

    @Autowired
    RiverService riverService;



    @GetMapping("/river")
    @ApiOperation("河流图数据")
    public ApiResponse<RiverVO> river(){
        List<RiverVO> riverVOS=new LinkedList<>();
        List<River> list = riverService.list();





        for (River t : list) {
            RiverVO riverVO = new RiverVO();
//            String[] arr = new String[3];
            LinkedList<String> list1 = new LinkedList<>();
            list1.add(t.getTime());
            list1.add(t.getValue());
            list1.add(t.getName());
            List<TMapW> list2 = new ArrayList<>(new HashSet<>(tMapWService.list(new LambdaQueryWrapper<TMapW>().eq(TMapW::getTopicName, t.getName()).eq(TMapW::getCategoryId, 1))));
            List<TMapW> list3 = new ArrayList<>(new HashSet<>(tMapWService.list(new LambdaQueryWrapper<TMapW>().eq(TMapW::getTopicName, t.getName()).eq(TMapW::getCategoryId, 2))));;

            //
            Set<TMapW> collect = list3.stream().filter(item -> {
                List<String> temp = list2.stream().map(TMapW::getWordName).collect(Collectors.toList());
                return temp.contains(item.getWordName());
            }).collect(Collectors.toSet());// 相当于common
            List<TMapW> list4 = new ArrayList<>(collect);

            List<String> coll = list4.stream().map(TMapW::getWordName).collect(Collectors.toList());// 共同词集合

            List<TMapW> collect2 = list2.stream().filter(obj -> {
                return !coll.contains(obj.getWordName());
            }).collect(Collectors.toList());
//
            List<TMapW> collect3 = list3.stream().filter(obj -> {
                return !coll.contains(obj.getWordName());
            }).collect(Collectors.toList());

            List<String> predefined_keywords = collect2.stream().map(TMapW::getWordName).collect(Collectors.toList());
            List<String> word_dis = collect3.stream().map(TMapW::getWordName).collect(Collectors.toList());
            List<String> common_words = list4.stream().map(TMapW::getWordName).collect(Collectors.toList());

            log.info("----------------------------------------------------父元素 预定义词: "+ predefined_keywords.size());

            log.info("----------------------------------------------------父元素 有value词: "+word_dis.size());
            log.info("----------------------------------------------------父元素 common词: "+common_words.size());

            riverVO.setData(list1).setPredefine_word(predefined_keywords).setWord_dis(word_dis).setCommon_words(common_words);
            riverVOS.add(riverVO);
        }
        return new ApiResponse(riverVOS);
    }

    @GetMapping("/getIndexData")
    @ApiOperation("堆叠图数据")
    public ApiResponse<IndexVO> getIndexData(){
        List<IndexVO> list=new LinkedList<>();

        for (int i = 1; i <=3; i++) {
            String time="2021-0";
            String s = String.valueOf(i);
            time+=s;
            IndexVO indexVO = new IndexVO();

            indexVO.setTime("2021-01");
            List<Topic> list1 = topicService.list(new LambdaQueryWrapper<Topic>().eq(Topic::getParentId, time + " politics"));
            List<TopicMinVO> topicMinVOS1 = BeanUtil.listA2ListB(list1, TopicMinVO.class);
            List<Topic> list2 = topicService.list(new LambdaQueryWrapper<Topic>().eq(Topic::getParentId, time + " economics"));
            List<TopicMinVO> topicMinVOS2 = BeanUtil.listA2ListB(list2, TopicMinVO.class);
            List<Topic> list3 = topicService.list(new LambdaQueryWrapper<Topic>().eq(Topic::getParentId, time + " social"));
            List<TopicMinVO> topicMinVOS3 = BeanUtil.listA2ListB(list3, TopicMinVO.class);
            indexVO.setTime(time).setPolitics(topicMinVOS1).setEconomics(topicMinVOS2).setSocial(topicMinVOS3);
            list.add(indexVO);
        }
        return new ApiResponse(list);
    }




//    @Transactional
//    @PostMapping("/addAll")
//    @ApiOperation("topic json  进行 load ")
//    public ApiResponse<Void> add(@RequestBody TopicPO[] po){
//        for (TopicPO p:po){
//            for (Long td:p.getDoc_list()){
//                //id 为realId连接
//                tMapDService.save(new TMapD().setDocumentId(td).setTopId(p.getId()).setTopName(p.getName()));
//            }
//            topicService.save(new Topic().setName(p.getName()).setRealId(p.getId()));
//            for (String word :p.getPredefined_keywords()){
//                tMapWService.save(new TMapW().setWordName(word).setTopId(p.getId()).setTopName(p.getName()).setCategoryId(1));
//            }
//
//            for (WordValue wv: p.getWord_dis()){
//                tMapWService.save(new TMapW().setWordName(wv.getKey()).setWordValue(wv.getValue()).setTopId(p.getId()).setTopName(p.getName()).setCategoryId(2));
//            }
//        }
//        return new ApiResponse<>();
//    }

//    @Transactional
//    @PostMapping("/addAll2")
//    @ApiOperation("load  Topic 文件 ")
//    public ApiResponse<Void> addFile(@RequestBody TopicPO[] po) throws IOException {
//        String jsonStr = "";
//        try {
//            File jsonFile = new File("C:\\Users\\jokehe\\Desktop\\topic.json");
//            FileReader fileReader = new FileReader(jsonFile);
//            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
//            int ch = 0;
//            StringBuffer sb = new StringBuffer();
//            while ((ch = reader.read()) != -1) {
//                sb.append((char) ch);
//            }
//            fileReader.close();
//            reader.close();
//            jsonStr = sb.toString();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        List<TopicPO> topicPOS = JSONObject.parseArray(jsonStr, TopicPO.class);
//
//        topicPOS.forEach(p->{
//            topicService.save(new Topic().setName(p.getName()).setRealId(p.getId()));
//        });
//        System.out.println("导入完成");
//        return new ApiResponse<>();
//    }


//
//
//    @Transactional
//    @PostMapping("/addAll3")
//    @ApiOperation("topic Tree关系  进行 load ")
//    public ApiResponse<Void> addTree(){
//        String jsonStr = "";
//        try {
//            File jsonFile = new File("C:\\Users\\jokehe\\Desktop\\2021-01.json");
//            FileReader fileReader = new FileReader(jsonFile);
//            Reader reader = new InputStreamReader(new FileInputStream(jsonFile),"utf-8");
//            int ch = 0;
//            StringBuffer sb = new StringBuffer();
//            while ((ch = reader.read()) != -1) {
//                sb.append((char) ch);
//            }
//            fileReader.close();
//            reader.close();
//            jsonStr = sb.toString();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        System.out.println(jsonStr);
//        List<TopicChildrenPOThree> topicChildrenPOThrees = JSONObject.parseArray(jsonStr, TopicChildrenPOThree.class);
//
//        System.out.println(topicChildrenPOThrees.size());
//        String timeLike="2021-01"; //2021-01 2021-02  2021-03
//
//        for (TopicChildrenPOThree tc: topicChildrenPOThrees){
//            // 获取父元素的real_Id ,时间去匹配唯一
//            Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().like(Topic::getRealId, timeLike).eq(Topic::getName, tc.getName()));
//            tMapLastnameService.save(new TMapLastname().setCreated(new Date()).setTopicId(one.getRealId()).setLastName(one.getName()));
//            updateChildren(tc.getChildren(),one.getRealId());
//        }
//        System.out.println("父子关系更新完成");
//        return new ApiResponse<>();
//    }
//
//
//    @Transactional
//    public void updateChildren(TopicChildren[] childrenArr,String  fatherId) {
//        if (childrenArr==null) return;
//        for (TopicChildren children :childrenArr){
//            // 存lastname
//            String[] lastname = children.getLastname();
//            for (String s:lastname){
//                tMapLastnameService.save(new TMapLastname().setCreated(new Date()).setTopicId(children.getId()).setLastName(s));
//            }
//
//
//            // 更新children 的 parentId  以及value
//            // Id 为realId
//            Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().eq(Topic::getRealId, children.getId()));
//            one.setParentId(fatherId);
//            one.setValue(children.getValue());
//            topicService.updateById(one);
//            updateChildren(children.getChildren(),children.getId());
//        }
//    }

    @Transactional
    @PostMapping("/getTopicMessage")
    @ApiOperation("根据topicId 获得词云柱状数据")
    public ApiResponse<TopicVO> get(@RequestParam String topicRealId){
        TopicVO topicVO = new TopicVO();
        Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().eq(Topic::getRealId, topicRealId));
        topicVO.setId(one.getRealId()).setName(one.getName()); // id和名字
        List<TMapW> list2 = new ArrayList<>(new HashSet<>(tMapWService.list(new LambdaQueryWrapper<TMapW>().eq(TMapW::getTopicId, one.getRealId()).eq(TMapW::getCategoryId, 1))));
        List<TMapW> list3 = new ArrayList<>(new HashSet<>(tMapWService.list(new LambdaQueryWrapper<TMapW>().eq(TMapW::getTopicId, one.getRealId()).eq(TMapW::getCategoryId, 2))));;
        List<TMapW> list4 = list3.stream().filter(item -> {
            List<String> coll = list2.stream().map(TMapW::getWordName).collect(Collectors.toList());
            return  coll.contains(item.getWordName());
        }).collect(Collectors.toList());// 相当于common

        List<TMapW> collect2 = list2.stream().filter(obj -> {
            List<String> coll = list4.stream().map(TMapW::getWordName).collect(Collectors.toList());
//            if (coll.contains(obj.getWordName())) System.out.println(obj.getWordName());
            return !coll.contains(obj.getWordName());
        }).collect(Collectors.toList());
//
        List<TMapW> collect3 = list3.stream().filter(obj -> {
            List<String> coll = list4.stream().map(TMapW::getWordName).collect(Collectors.toList());
            return !coll.contains(obj.getWordName());
        }).collect(Collectors.toList());


        List<WordModel> predefined_keywords = BeanUtil.listA2ListB(collect2, WordModel.class);
//            List<String> predefined_words = predefined_keywords.stream().map(WordModel::getWordName).collect(Collectors.toList());
        List<WordModel> word_dis = BeanUtil.listA2ListB(collect3, WordModel.class);


        List<WordModel> common_words = BeanUtil.listA2ListB(list4, WordModel.class);
        topicVO.setWord_dis(word_dis).setPredefined_keywords(predefined_keywords).setCommon_words(common_words);// 三种对应词
        log.info("----------------------------------------------------父元素 预定义词: "+ predefined_keywords.size());

        log.info("----------------------------------------------------父元素 有value词: "+word_dis.size());
        log.info("----------------------------------------------------父元素 common词: "+common_words.size());
        // 获取子元素

        List<Topic> topicTotalList = topicService.list(new LambdaQueryWrapper<Topic>()).stream().filter(t->t.getParentId()!=null).collect(Collectors.toList());// 获取所有子topic

        return new ApiResponse(topicVO);
    }
//
//    private List<TopicVO> getTopicChildren(String topicRealId, List<Topic> topicTotalList) {
//
////        List<Topic> childrenList = topicService.list(new LambdaQueryWrapper<Topic>().eq(Topic::getParentId, topicRealId));
//        List<Topic> childrenList = topicTotalList.stream().filter(t -> t.getParentId().equals(topicRealId) ).collect(Collectors.toList());;
//
//        if (childrenList.size()==0) return  null;
//
//        List<TopicVO> children=new LinkedList<>();
//        childrenList.stream().forEach(t->{
//            TopicVO topicVO = new TopicVO();
//            topicVO.setId(t.getRealId()).setName(t.getName()).setValue(t.getValue()); // id和名字和value
//            List<TMapW> list2 = new ArrayList<>(new HashSet<>(tMapWService.list(new LambdaQueryWrapper<TMapW>().eq(TMapW::getTopId, t.getRealId()).eq(TMapW::getCategoryId, 1))));
//            List<TMapW> list3 = new ArrayList<>(new HashSet<>(tMapWService.list(new LambdaQueryWrapper<TMapW>().eq(TMapW::getTopId, t.getRealId()).eq(TMapW::getCategoryId, 2))));;
//
//            List<TMapW> list4 = list3.stream().filter(item -> {
//                List<String> coll = list2.stream().map(TMapW::getWordName).collect(Collectors.toList());
//                return  coll.contains(item.getWordName());
//            }).collect(Collectors.toList());
//
//            List<TMapW> collect2 = list2.stream().filter(obj -> {
//                List<String> coll = list4.stream().map(TMapW::getWordName).collect(Collectors.toList());
//                return !coll.contains(obj.getWordName());
//            }).collect(Collectors.toList());
//
//            List<TMapW> collect3 = list3.stream().filter(obj -> {
//                List<String> coll = list4.stream().map(TMapW::getWordName).collect(Collectors.toList());
//                return !coll.contains(obj.getWordName());
//            }).collect(Collectors.toList());
//
//
//            List<WordModel> predefined_keywords = BeanUtil.listA2ListB(collect2, WordModel.class);
//            List<WordModel> word_dis = BeanUtil.listA2ListB(collect3, WordModel.class);
//            List<WordModel> common_words = BeanUtil.listA2ListB(list4, WordModel.class);
//            topicVO.setWord_dis(word_dis).setPredefined_keywords(predefined_keywords).setCommon_words(common_words);// 三种对应词
//            log.info("----------------------------------------------------预定义词: "+predefined_keywords.size()+t.getRealId());
//            log.info("----------------------------------------------------有value词: "+word_dis.size());
//            log.info("----------------------------------------------------common词: "+common_words.size());
//
//            // 获取子元素
//            List<TopicVO> children2 = getTopicChildren(t.getRealId(), topicTotalList);
//            topicVO.setChildren(children2);
//            children.add(topicVO);
//        });
//        return children;
//    }



    @Transactional
    @PostMapping("/getSunData")
    @ApiOperation("根据topicId 获得太阳图数据")
    public ApiResponse<TopicVO> getSunData(@RequestParam String topicRealId){
        TopicVO topicVO = new TopicVO();
        Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().eq(Topic::getRealId, topicRealId));
        topicVO.setId(one.getRealId()).setName(one.getName()); // id和名字
        // 获取子元素
        List<Topic> topicTotalList = topicService.list(new LambdaQueryWrapper<Topic>()).stream().filter(t->t.getParentId()!=null).collect(Collectors.toList());// 获取所有子topic
        List<TopicVO> children = getTopicChildren2(one.getRealId(),topicTotalList);
        topicVO.setChildren(children);
        return new ApiResponse(topicVO);
    }

    private List<TopicVO> getTopicChildren2(String topicRealId, List<Topic> topicTotalList) {

//        List<Topic> childrenList = topicService.list(new LambdaQueryWrapper<Topic>().eq(Topic::getParentId, topicRealId));
        List<Topic> childrenList = topicTotalList.stream().filter(t -> t.getParentId().equals(topicRealId) ).collect(Collectors.toList());;

        if (childrenList.size()==0) return  null;

        List<TopicVO> children=new LinkedList<>();
        childrenList.stream().forEach(t->{
            TopicVO topicVO = new TopicVO();
            topicVO.setId(t.getRealId()).setName(t.getName()).setValue(t.getValue()); // id和名字和value
            // 获取子元素
            List<TopicVO> children2 = getTopicChildren2(t.getRealId(), topicTotalList);
            topicVO.setChildren(children2);
            children.add(topicVO);
        });
        return children;
    }



    @Transactional
    @PostMapping("/getTopicDocument")
    @ApiOperation("根据topicId 获得Document信息")
    public ApiResponse<TopicVO> getdocument(@RequestParam String topicRealId){
        TopicVO topicVO = new TopicVO();
        Topic one = topicService.getOne(new QueryWrapper<Topic>().eq("real_id", topicRealId));
        Topic byId = topicService.getById(1014L);
        topicVO.setId(one.getRealId()).setName(one.getName()); // id和名字
        //---------
        List<TMapD> list1 = tMapDService.list(new LambdaQueryWrapper<TMapD>().eq(TMapD::getTopId, one.getRealId()));
        List<Long> collect1 = list1.stream().map(TMapD::getDocumentId).collect(Collectors.toList());
        List<Document> documents = documentService.listByIds(collect1);
        List<DocumentModel> documentModels = BeanUtil.listA2ListB(documents, DocumentModel.class);
        topicVO.setDoc_list(documentModels);//  documentModel
        return new ApiResponse(topicVO);
    }







    @Transactional
    @PostMapping("/getLastName")
    @ApiOperation("根据topicId 获得Topic的LastName")
    public ApiResponse<TMapLastname> getLastName(@RequestParam String topicRealId) {

        Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().eq(Topic::getRealId, topicRealId));
        List<TMapLastname> lastname_list = tMapLastnameService.list(new LambdaQueryWrapper<TMapLastname>().eq(TMapLastname::getTopicId, one.getRealId())).stream().sorted(Comparator.comparing(TMapLastname::getCreated).reversed()).collect(Collectors.toList());

        return new ApiResponse(lastname_list);
    }

    @Transactional
    @PostMapping("/deleteLastName")
    @ApiOperation("根据对应的Id 删除Topic 的lastname")
    public ApiResponse deleteLastName(@RequestParam String tMapLastNameId) {
        boolean b = tMapLastnameService.removeById(tMapLastNameId);
        if (!b) throw new BusException("删除失败");
        return new ApiResponse("删除成功");
    }

    @Transactional
    @PostMapping("/addLastName")
    @ApiOperation("根据topicId 增加Topic 的lastname")
    public ApiResponse addLastName(@RequestParam String topicRealId,@RequestParam String add_lastname) {

        Topic one = topicService.getOne(new LambdaQueryWrapper<Topic>().eq(Topic::getRealId, topicRealId));
        one.setName(add_lastname);
        topicService.updateById(one);//更新
        TMapLastname new_lastname = new TMapLastname();
        new_lastname.setTopicId(one.getRealId());
        new_lastname.setLastName(add_lastname);
        List<TMapLastname> list = tMapLastnameService.list(new LambdaQueryWrapper<TMapLastname>().eq(TMapLastname::getTopicId, topicRealId).eq(TMapLastname::getLastName, add_lastname));
        if (list.size()>0) throw new BusException("增加失败,名字已存在");
        Boolean isSuccess = tMapLastnameService.save(new_lastname);
        if (!isSuccess) throw new BusException("增加失败");
        return new ApiResponse("增加成功");
    }



}

